/*
 * @Date: 2021-11-16 16:02:21
 * @Version: 0.0.1
 * @Author: chenhengling
 * @Description: download
 * @LastEditTime: 2021-11-17 20:29:47
 * @LastEditors: chenhengling
 */
const path = require('path');
const os = require('os');
const fs = require('fs');
const download = require('download-git-repo');
const parse = require('url-parse');

function removeGitCredential(credential) {
  try {
    const gitCredentialPath = path.join(os.homedir(), '.git-credentials');
    if (fs.existsSync(gitCredentialPath)) {
      let result = fs.readFileSync(gitCredentialPath, 'utf-8');
      result = result.replace(RegExp(credential + '\\s*', 'g'), '');
      fs.writeFileSync(gitCredentialPath, result, 'utf-8');
    }
  } catch (error) {}
}

function main(template, localPath) {
  return new Promise((resolve, reject) => {
    if (template && template.url) {
      try {
        let url = template.url;
        let credential;

        if (template.token) {
          const { protocol, hostname, pathname } = parse(url);
          credential = `${protocol}//oauth2:${template.token}@${hostname}`;
          url = `${credential + pathname}`;
        }

        download(`direct:${url}`, localPath, { clone: true }, (err) => {
          // 删除git凭证
          credential && removeGitCredential(credential);

          if (err) {
            reject(err);
          } else {
            resolve();
          }
        });
      } catch (err) {
        reject(new Error('创建模板出错'));
      }
    } else {
      reject(new Error('未找到该类型模板'));
    }
  });
}

module.exports = main;

if (require.main === module) {
  // removeGitCredential();
}
